package info.batcloud.fanli.core.item.collection;

import com.alibaba.fastjson.JSON;
import com.ctospace.archit.common.pagination.Paging;
import info.batcloud.fanli.core.dto.CommissionItemFetchDTO;
import info.batcloud.fanli.core.enums.CommissionItemStatus;
import info.batcloud.fanli.core.enums.EcomPlat;
import info.batcloud.fanli.core.enums.ItemSelectionType;
import info.batcloud.pdd.sdk.PddClient;
import info.batcloud.pdd.sdk.domain.ddk.Goods;
import info.batcloud.pdd.sdk.request.ddk.GoodsSearchRequest;
import info.batcloud.pdd.sdk.response.ddk.GoodsSearchResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.inject.Inject;
import java.util.*;
import java.util.function.Consumer;

@Component
public class DdkGoodsSearchSelectionCollector extends AbstractItemSelectionCollector<DdkGoodsSearchCollectContext> {

    private static final Logger logger = LoggerFactory.getLogger(DdkGoodsSearchSelectionCollector.class);

    @Inject
    private PddClient pddClient;

    @Override
    public CollectResult collect(DdkGoodsSearchCollectContext context,
                                 Consumer<Paging<CommissionItemFetchDTO>> pagingConsumer) {
        CollectResult result = new CollectResult();
        GoodsSearchRequest request = new GoodsSearchRequest();
        request.setPageSize(context.getPageSize());
        if (context.getCatId() != null) {
            request.setCatId(context.getCatId());
        }
        if (StringUtils.isNotBlank(context.getKeyword())) {
            request.setKeyword(context.getKeyword());
        }
        if (StringUtils.isNotBlank(context.getGoodsIdList())) {
            request.setGoodsIdList(JSON.toJSONString(Arrays.asList(context.getGoodsIdList().split(","))));
        }
        if (context.getMerchantType() != null) {
            request.setMerchantType(context.getMerchantType());
        }
        if (context.getSortType() != null) {
            request.setSortType(context.getSortType());
        }
        request.setWithCoupon(context.isWithCoupon());
        try {
            int page = context.getStartPage();
            int num = 0;
            request.setPageSize(30);
            while (true) {
                logger.info("同步" + page + "页");
                request.setPage(page);
                GoodsSearchResponse response = pddClient.execute(request);
                GoodsSearchResponse.Data data = response.getData();
                int total = data.getTotalCount();
                List<Goods> list = data.getGoodsList();
                if (list == null) {
                    break;
                }
                List<CommissionItemFetchDTO> ciList = new ArrayList<>();
                for (Goods goods : data.getGoodsList()) {
                    ciList.add(toCommissionItem(context, goods));
                }
                Paging<CommissionItemFetchDTO> paging = new Paging<>();
                paging.setResults(ciList);
                paging.setPage(page);
                paging.setPageSize(context.getPageSize());
                paging.setTotal(data.getTotalCount());
                pagingConsumer.accept(paging);
                num += list.size();
                if (total <= num) {
                    break;
                }
                if (list.size() < 30) {
                    break;
                }
                if (page >= context.getMaxPage()) {
                    break;
                }
                page++;
            }
            logger.info("同步完成");
            result.setSuccess(true);
            result.setTotalNum(num);
        } catch (Exception e) {
            logger.error("同步失败", e);
            result.setSuccess(false);
            result.setErrMsg(e.getLocalizedMessage());
        }
        return result;
    }

    private static CommissionItemFetchDTO toCommissionItem(DdkGoodsSearchCollectContext context, Goods goods) {
        CommissionItemFetchDTO dto = new CommissionItemFetchDTO();
        Date now = new Date();
        dto.setListTime(now);
        /**
         * 商品的下架时间为当前的日期+7天，优惠券的下架时间，活动的下架时间取最大者
         * */
        Date delistTime = DateUtils.addDays(now, 7);
        dto.setCoupon(goods.getCouponStartTime() > 0);
        Date couponEndTime;
        if (goods.getCouponEndTime() > 0) {
            couponEndTime = new Date(goods.getCouponEndTime());
        } else {
            couponEndTime = new Date();
        }
        dto.setDelistTime(Collections.max(Arrays.asList(delistTime, couponEndTime)));
        dto.setCouponStartTime(goods.getCouponStartTime() > 0 ? new Date(goods.getCouponStartTime()) : null);
        dto.setSourceCatIdList(goods.getCatIds());
        dto.setShopTitle(goods.getMallName());
        dto.setCouponRemainCount(Long.valueOf(goods.getCouponRemainQuantity()).intValue());
        dto.setCouponTotalCount(Long.valueOf(goods.getCouponTotalQuantity()).intValue());

        dto.setCouponValue(goods.getCouponDiscount() / 100f);
        dto.setSourceItemUrl("");
        dto.setSourceItemId(goods.getGoodsId());
        dto.setTitle(goods.getGoodsName());
        dto.setSourceItemClickUrl("");
        dto.setCouponClickUrl("");
        dto.setOriginPrice(goods.getMinGroupPrice() / 100f);
        float couponStartFee = goods.getCouponMinOrderAmount() / 100f;
        dto.setCouponThresholdAmount(couponStartFee);
        dto.setCommissionRate(goods.getPromotionRate() / 10);
        dto.setEcomPlat(EcomPlat.PDD);
        dto.setSeckill(false);
        dto.setImgList(new ArrayList<>());
        dto.setPicUrl(StringUtils.defaultIfBlank(goods.getGoodsImageUrl(),
                goods.getGoodsThumbnailUrl()));
        dto.setSales(goods.getSoldQuantity());
        dto.setStatus(CommissionItemStatus.ONSALE);
        dto.setChannelId(context.getChannelId());
        dto.setShopcatId(context.getShopcatId());
        dto.setRecommend(context.isRecommend());
        return dto;
    }

    @Override
    public Class<DdkGoodsSearchCollectContext> getContextType() {
        return DdkGoodsSearchCollectContext.class;
    }

    @Override
    protected ItemSelectionType getItemSelectionType() {
        return ItemSelectionType.DDK_GOODS;
    }
}
